/*
 * @lc app=leetcode.cn id=707 lang=typescript
 *
 * [707] 设计链表
 */

// @lc code=start
class MyLinkedList {
    private head: LinkNode;
    private size: number;
    constructor() {
        this.head = new LinkNode(-1);
        this.size = 0;
    }

    get(index: number): number {
        if (index < 0 || index >= this.size) {
            return -1;
        }
        let cur = this.head;
        for (let i = 0; i <= index; i++) {
            cur = cur.next!
        }
        return cur.val;
    }

    addAtHead(val: number): void {
        this.addAtIndex(0, val);
    }

    addAtTail(val: number): void {
        this.addAtIndex(this.size, val);
    }

    addAtIndex(index: number, val: number): void {
        if (index > this.size) {
            return;
        }
        index = Math.max(0, index);
        this.size++;
        let pre = this.head;
        for (let i = 0; i < index; i++) {
            pre = pre.next!;
        }
        let v = new LinkNode(val);
        v.next = pre.next;
        pre.next = v;
    }

    deleteAtIndex(index: number): void {
        if (index < 0 || index >= this.size) {
            return;
        }
        this.size--;
        let pred = this.head;
        for (let i = 0; i < index; i++) {
            pred = pred.next!;
        }
        pred.next = pred.next!.next;
    }
}

class LinkNode {
    val: number
    next: LinkNode | null
    constructor(val: number) {
        this.val = val;
        this.next = null;
    }
}

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * var obj = new MyLinkedList()
 * var param_1 = obj.get(index)
 * obj.addAtHead(val)
 * obj.addAtTail(val)
 * obj.addAtIndex(index,val)
 * obj.deleteAtIndex(index)
 */
// @lc code=end

